﻿using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace NetC100KTest
{
    public class SessionPool
    {
        private Bootstrap _bootstrap;
        private MultithreadEventLoopGroup _group;
        private List<IChannel> _channel;

        public SessionPool()
        {
            _channel = new List<IChannel>();
            _group = new MultithreadEventLoopGroup();
            _bootstrap = new Bootstrap();
            _bootstrap.Group(_group)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                        {
                            IChannelPipeline pipeline = channel.Pipeline;
                            pipeline.AddLast(new SessionHandler());
                        }));
        }

        public async Task<IChannel> ConnectAsync(IPEndPoint remoteAddress, IPEndPoint localAddress)
        {
            try
            {
                var channel = await _bootstrap.ConnectAsync(remoteAddress, localAddress);
                return channel;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return null;
            }
        }

        public void Dispose()
        {
            if (_group != null)
                _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
        }
    }
}
